package com.example.multithread;

import android.os.Bundle;
import android.os.HandlerThread;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadActivity extends AppCompatActivity {
    public static final String TAG = ThreadActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // 方式1： 匿名类启动线程
        new Thread("Thread匿名类线程") {
            @Override
            public void run() {
                Log.i(TAG, Thread.currentThread().getName());
            }
        }.start();
        // 方式2：启动线程
        new MyThread("MyThead").start();

        // 方式1：匿名类实现Runnable接口
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, Thread.currentThread().getName());
            }
        }).start();
        // 方式2启动线程
        new Thread(new MyRunnable()).start();

        // 使用Callback和Future接口
        final FutureTask<Integer> task = new FutureTask<>(new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int i = 10;
                Log.i(TAG, Thread.currentThread().getName() + i);
                return i;
            }
        });
        // 启动线程
        new Thread(task, "有返回值的线程").start();

        try {
            Log.i(TAG, "task返回值为" + task.get());
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 方式2： 继承Thread类
    static class MyThread extends Thread {
        public MyThread(@NonNull String name) {
            super(name);
        }

        @Override
        public void run() {
            Log.i(TAG, Thread.currentThread().getName());
        }
    }

    // 方式2：实现Runnable接口
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            Log.i(TAG, Thread.currentThread().getName());
        }
    }
}